package dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import entity.SchoolClass;
import entity.LabReservation;
import util.JDBCUtil;

public class ClassDAO {

    // 添加班级
    public boolean addClass(SchoolClass clazz) {
        String sql = "INSERT INTO class (class_id, class_name, teacher_id) VALUES (?, ?, ?)";
        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, clazz.getClassId());
            pstmt.setString(2, clazz.getClassName());
            pstmt.setInt(3, clazz.getTeacherId());
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 根据学生ID获取所在班级
    public SchoolClass getClassByStudentId(int studentId) {
        String sql = "SELECT c.* FROM class c " +
                "JOIN user u ON c.class_id = u.class_id " +
                "WHERE u.user_id = ?";
        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, studentId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return new SchoolClass(
                        rs.getInt("class_id"),
                        rs.getString("class_name"),
                        rs.getInt("teacher_id")
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据班级ID获取班级信息
     */
    public SchoolClass getClassById(int classId) {
        String sql = "SELECT * FROM class WHERE class_id = ?";
        try (Connection conn = JDBCUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, classId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                return new SchoolClass(
                        rs.getInt("class_id"),
                        rs.getString("class_name"),
                        rs.getInt("teacher_id")
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}